//
//  BDVerifyLoginTableViewController.m
//  BeidouMall
//
//  Created by qie on 16/4/3.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDVerifyLoginTableViewController.h"

@interface BDVerifyLoginTableViewController ()
{
    NSTimer *_timer;
    NSInteger _count;
}
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
@property (weak, nonatomic) IBOutlet UITextField *verfiyTextField;

@property (weak, nonatomic) IBOutlet UIButton *getVerifactionButton;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;


@property (strong,nonatomic)NSDictionary *userInfo;

@end

@implementation BDVerifyLoginTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"验证码登录";
    
    self.bottomView.height = kScreen_Height - 230;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

#pragma mark - TextField delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *futrueString = [textField.text changeCharactersInRange:range replacementString:string];
    
    if ([_accountTextField.text length]
        && [_verfiyTextField.text length]) {
        _loginButton.enabled = YES;
    } else {
        _loginButton.enabled = NO;
    }
    
    if (textField.tag == 101) {
        if (futrueString.length > kUserNameLength) {
            return NO;
        }
    } else if (textField.tag == 102) {
        if (futrueString.length > kVerificationMaxLength) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 101) {
        [_accountTextField becomeFirstResponder];
    } else if (textField.tag == 102) {
        [_verfiyTextField becomeFirstResponder];
    }
    return YES;
}

#pragma mark - scrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (_accountTextField.isFirstResponder) {
        [_accountTextField resignFirstResponder];
    } else if (_verfiyTextField.isFirstResponder) {
        [_verfiyTextField resignFirstResponder];
    }
}

#pragma mark - Private method

- (void)updateRequestVerifyCodeButton {
    if (--_count > 0) {
        [_getVerifactionButton setTitle:[NSString stringWithFormat:@"%ld秒后重发",(long)_count] forState:UIControlStateDisabled];
    } else {
        _getVerifactionButton.enabled = YES;
        _getVerifactionButton.backgroundColor = kButtonEnableColor;
        NSString *promit = [NSString stringWithFormat:@"%d秒后重发",kWaitTime];
        [_getVerifactionButton setTitle:promit forState:UIControlStateDisabled];
        [_timer invalidate];
    }
}

#pragma mark - IBAction

- (IBAction)getVerificationButtonPressed:(UIButton *)sender {
    if (_accountTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"账号为空"];
    } else if (!([_accountTextField.text isValidPhoneNum] || [_accountTextField.text isVaildEmail])) {
        [MBProgressHUD showToast:self.view withText:@"账号格式不正确"];
    } else {
        
        if (_timer != nil) {
            [_timer invalidate];
        }
        
        NSString *url = [NSString stringWithFormat:@"%@%@?account=%@&type=%@",[BDNetworking shareInstance].baseUrl,VerifyCode,_accountTextField.text,BUYER_LOGIN];
        [[BDAccountManagerModel shareInstance] getVerifyCodeWithUrl:url  completionHandler:^(NSError *error) {
            if (error != nil) {
                NSLog(@"验证码:失败%@",[error localizedDescription]);
                NSString *errorStr = [NSString stringWithFormat:@"验证码获取失败:%@",[error localizedDescription]];
                [MBProgressHUD showToast:self.view withText:errorStr];
                [_timer invalidate];
                dispatch_async(dispatch_get_main_queue(), ^{// 更新UI操作必须在主线程
                    sender.enabled = YES;
                    sender.backgroundColor = kButtonEnableColor;
                    [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                });
            } else {
                
            }
        }];
        
        _count = kWaitTime;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateRequestVerifyCodeButton) userInfo:nil repeats:YES];
        sender.enabled = NO;
        sender.backgroundColor = sender.enabled ? kButtonEnableColor : kButtonDisEnableColor;
    }
    
}

- (IBAction)nextStepButtonPressed:(UIButton *)sender {
    if (_accountTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"账号为空"];
    } else if (!([_accountTextField.text isValidPhoneNum] || [_accountTextField.text isVaildEmail])) {
        [MBProgressHUD showToast:self.view withText:@"账号格式不正确"];
    } else if (_verfiyTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:@"验证码为空"];
    } else if (![_verfiyTextField.text isVaildVerificationCode]) {
        [MBProgressHUD showToast:self.view withText:@"验证码格式不正确"];
    } else {
        if (_accountTextField.isFirstResponder) {
            [_accountTextField resignFirstResponder];
        } else if (_verfiyTextField.isFirstResponder) {
            [_verfiyTextField resignFirstResponder];
        }
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@"正在登录"];
        
        NSString *url = [NSString stringWithFormat:@"%@%@",[BDNetworking shareInstance].baseUrl,LOGIN_IN_Verify];
        [[BDAccountManagerModel shareInstance] verifyLoginWithUrl:url
                                                         username:_accountTextField.text
                                                       verifyCode:_verfiyTextField.text
                                                         userType:BUYER
                                                             flag:@"NO"
                                                completionHandler:^(NSDictionary *results, NSError *error) {
                                                    if (error != nil) {
                                                        NSLog(@"登录失败%@", [error localizedDescription]);
                                                        hud.labelText = [error localizedDescription];
                                                        [hud hideAfterDelay:0.5];
                                                    } else {
                                                        self.userInfo = results;
                                                        hud.labelText = @"登录成功";
                                                        [hud hideAfterDelay:0.5];
                                                        
                                                        dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC);
                                                        dispatch_after(time, dispatch_get_main_queue(), ^{
                                                            [self dismissViewControllerAnimated:YES completion:nil];
                                                        });
                                                    }
                                                }];
    }
}

@end
